/*
 * Copyright (c) 2024 Shenzhen Kaihong Digital Industry Development Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

#include <unistd.h>
#include "iservice_registry.h"
#include "i_sle_host.h"
#include "sle_announce_impl.h"
#include "sle_common_config.h"
#include "sle_hilog.h"

namespace OHOS {
namespace NearLink {
namespace SleStandard {
SleAnnounce::SleAnnounceImpl::SleAnnounceImpl()
{
    SLE_LOGI("SleAnnounceImpl In");
    callbackImpl_ = new SleAnnounceCallbackStubImpl(*this);
    SLE_ASSERT_AND_RETURN_LOG(callbackImpl_, "callbackImpl null error!");

    auto resetCallback = [this](const wptr<IRemoteObject> &remote) { this->ResetService(remote); };
    deathRecipient_ = new SleDeathRecipient(resetCallback);
    SLE_ASSERT_AND_RETURN_LOG(deathRecipient_, "deathRecipient null error!");

    std::lock_guard<std::mutex> lock(mutexProxy_);
    GetProxy();
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "get proxy error!");
}

SleAnnounce::SleAnnounceImpl::~SleAnnounceImpl()
{
    SLE_LOGI("~SleAnnounceImpl In");
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "announce proxy null error!");
    SLE_ASSERT_AND_RETURN_LOG(callbackImpl_, "callbackImpl null error!");
    SleErrorCode ret = proxy_->UnregisterAnnounceCallback(callbackImpl_);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "unregister announce callback failed(%{public}d)!", ret);
}

void SleAnnounce::SleAnnounceImpl::GetProxy()
{
    if (proxy_) {
        return;
    }
    SLE_LOGI("GetProxy In");
    sptr<ISystemAbilityManager> samgr = SystemAbilityManagerClient::GetInstance().GetSystemAbilityManager();
    SLE_ASSERT_AND_RETURN_LOG(samgr, "no samgr error!");

    sptr<IRemoteObject> hostRemote = samgr->GetSystemAbility(KH_SLE_SERVICE_SYS_ABILITY_ID_);

    SLE_ASSERT_AND_RETURN_LOG(hostRemote, "no remote error!");
    sptr<ISleHost> hostProxy = iface_cast<ISleHost>(hostRemote);
    SLE_ASSERT_AND_RETURN_LOG(hostProxy, "host proxy null error!");

    sptr<IRemoteObject> remote = hostProxy->GetSleServerRemote(SLE_ANNOUNCE_SERVER);
    SLE_ASSERT_AND_RETURN_LOG(remote, "no remote error!");

    SLE_ASSERT_AND_RETURN_LOG(deathRecipient_, "deathRecipient null error!");
    SLE_ASSERT_AND_RETURN_LOG(!((remote->IsProxyObject()) && (!remote->AddDeathRecipient(deathRecipient_))),
        "Failed to add death recipient");

    proxy_ = iface_cast<ISleAnnounce>(remote);
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "no announce proxy error!");
    SleErrorCode ret = proxy_->RegisterAnnounceCallback(callbackImpl_);
    SLE_ASSERT_AND_RETURN_LOG(ret == SLE_NO_ERROR, "register announce callback failed(%{public}d)!", ret);
    SLE_LOGI("GetProxy success");
}

void SleAnnounce::SleAnnounceImpl::ResetService(const wptr<IRemoteObject> &remote)
{
    SLE_ASSERT_AND_RETURN_LOG(remote != nullptr, "remote null error!");
    std::lock_guard<std::mutex> lock(mutexProxy_);
    SLE_ASSERT_AND_RETURN_LOG(proxy_, "no proxy error!");
    sptr<IRemoteObject> serviceRemote = proxy_->AsObject();
    if ((serviceRemote != nullptr) && (serviceRemote == remote.promote())) {
        serviceRemote->RemoveDeathRecipient(deathRecipient_);
        proxy_ = nullptr;
        int tryTime = 5;
        while ((!proxy_) && tryTime > 0) {
            sleep(GET_PROXY_SLEEP_SEC);
            tryTime--;
            GetProxy();
        }
    }
}

SleErrorCode SleAnnounce::SleAnnounceImpl::CheckOperation()
{
    std::lock_guard<std::mutex> lock(mutexProxy_);
    GetProxy();
    SLE_ASSERT_AND_RETURN_RET_LOG(proxy_, SLE_ERR_INTERNAL_WRONG, "proxy null error!");
    return SLE_NO_ERROR;
}

SleAnnounce::SleAnnounce()
{
    pimpl_ = std::make_unique<SleAnnounceImpl>();
    SLE_ASSERT_AND_RETURN_LOG(pimpl_, "pimpl null error!");
}

SleAnnounce::~SleAnnounce(){}

SleErrorCode SleAnnounce::AddAnnounce(uint8_t &announceId)
{
    SLE_LOGD("AddAnnounce In");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->proxy_->CreateAnnounceId(announceId);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "alloc announce id failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleAnnounce::RemoveAnnounce(uint8_t announceId)
{
    SLE_LOGD("RemoveAnnounce In");
    SLE_ASSERT_AND_RETURN_RET_LOG(announceId >= 1 && announceId <= SLE_MAX_ANNOUNCE_ID_NUM, SLE_ERR_INTERNAL_WRONG,
        "param announce id error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);
    ret = pimpl_->proxy_->RemoveAnnounceId(announceId);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "recovery announce id failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleAnnounce::StartAnnounce(uint8_t announceId, SleAnnounceData &data, const SleAnnounceParam &param)
{
    SLE_LOGD("StartAnnounce In");
    SLE_ASSERT_AND_RETURN_RET_LOG(announceId >= 1 && announceId <= SLE_MAX_ANNOUNCE_ID_NUM, SLE_ERR_INTERNAL_WRONG,
        "param announce id error!");
    SleErrorCode ret = AnnounceData::CheckAnnounceData(data);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check data failed(%{public}d)!", ret);
    ret = AnnounceParam::CheckAnnounceParam(param);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check param failed(%{public}d)!", ret);
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);

    AnnounceData datas(data);
    AnnounceParam params(param);
    ret = pimpl_->proxy_->StartAnnounce(announceId, datas, params);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "start announce failed(%{public}d)!", ret);

    std::unique_lock<std::mutex> lock(pimpl_->mtx_);
    auto status = pimpl_->conditionVariable_.wait_for(lock, std::chrono::milliseconds(3000), [this] { return pimpl_->ready_; });
    pimpl_->ready_ = false;
    if (!status) {
        SLE_LOGE("timeout, start announce failed(%{public}d)!", ret);
        return SLE_ERR_TIME_OUT;
    }
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->state_ == SLE_ANNOUNCE_ENABLED_STATE, SLE_ERR_FAILED, "start announce failed!(%s)",
        SleAnnounceStateStr(pimpl_->state_));
    return SLE_NO_ERROR;
}

SleErrorCode SleAnnounce::StopAnnounce(uint8_t announceId)
{
    SLE_LOGD("StopAnnounce In");
    SLE_ASSERT_AND_RETURN_RET_LOG(announceId >= 1 && announceId <= SLE_MAX_ANNOUNCE_ID_NUM, SLE_ERR_INTERNAL_WRONG,
        "param announce id error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed(%{public}d)!", ret);

    ret = pimpl_->proxy_->StopAnnounce(announceId);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "start announce failed(%{public}d)!", ret);

    std::unique_lock<std::mutex> lock(pimpl_->mtx_);
    auto status = pimpl_->conditionVariable_.wait_for(lock, std::chrono::milliseconds(3000), [this] { return pimpl_->ready_; });
    pimpl_->ready_ = false;
    if (!status) {
        SLE_LOGE("timeout, stop announce failed(%{public}d)!", ret);
        return SLE_ERR_TIME_OUT;
    }
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->state_ == SLE_ANNOUNCE_DISABLED_STATE, SLE_ERR_FAILED, "stop announce failed(%s)!",
        SleAnnounceStateStr(pimpl_->state_));
    return SLE_NO_ERROR;
}

SleErrorCode SleAnnounce::GetDefaultAnnounceParamConfig(SleAnnounceParam &announceConfig)
{
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SleErrorCode ret = pimpl_->CheckOperation();
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, SLE_ERR_CHECKOUT_FAILED, "check operation failed!");
    ret = pimpl_->proxy_->GetDefaultAnnounceParamConfig(announceConfig);
    SLE_ASSERT_AND_RETURN_RET_LOG(ret == SLE_NO_ERROR, ret, "get announce param config failed(%{public}d)!", ret);
    return SLE_NO_ERROR;
}

SleErrorCode SleAnnounce::RegisterAnnounceCallback(std::shared_ptr<SleAnnounceCallback> callback)
{
    SLE_LOGD("RegisterAnnounceCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback, SLE_ERR_INVALID_PARAM, "param callback nullptr error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->callbacks_.Register(callback), SLE_ERR_FAILED,
        "register announce callback failed!");
    return SLE_NO_ERROR;
}

SleErrorCode SleAnnounce::UnregisterAnnounceCallback(std::shared_ptr<SleAnnounceCallback> callback)
{
    SLE_LOGD("UnregisterAnnounceCallback In");
    SLE_ASSERT_AND_RETURN_RET_LOG(callback, SLE_ERR_INVALID_PARAM, "param callback nullptr error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_, SLE_ERR_INTERNAL_WRONG, "pimpl null error!");
    SLE_ASSERT_AND_RETURN_RET_LOG(pimpl_->callbacks_.Unregister(callback), SLE_ERR_FAILED,
        "unregister announce callback failed!");
    return SLE_NO_ERROR;
}
} // SleStandard
} // NearLink
} // OHOS